package com.itheima.service.backend.impl;

import com.itheima.mapper.backend.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 自定义用户详情服务类
 */
@Service
public class SpringSecurityUserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    private User user;//用户对象
    private Role role;//角色对象
    private List<GrantedAuthority> list;//权限集合
    private UserDetails userDetails;//用户详情

    /**
     * 根据用户名查询用户详情
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        user = userMapper.findByUsername(username);
        list = new ArrayList<>();
        if (user != null) {
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                Set<Permission> permissions = userMapper.findPermissionsByRoleId(role.getId());
                for (Permission permission : permissions) {
                    list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    list.add(new SimpleGrantedAuthority(role.getKeyword()));
                    list.add(new SimpleGrantedAuthority("ROLE_"+role.getKeyword()));
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
    }
}
